//
//  AddressListController.swift
//  swiftProject
//
//  Created by ZhangSai on 2021/7/5.
//

import UIKit

class AddressListController: ZsBaseViewController,UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate {

    typealias AddressListBlock = (_ userAddressModel:AddressModel,_ index:Int) -> Void
    var selectAddressBlock : AddressListBlock!
    var index:Int!
    var resultStr:String = ""
    var dataSource = Array<AddressModel>()
    var searchArr = Array<AddressModel>()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.WL_lookExpress)
        self.view.backgroundColor = UIColor.init(hexString: "#F3F3F3")
        self.getData()
        self.setUI()
    }
    
    func getData() {
        Constants.window?.makeToastActivity(.center)
        HttpService.sharedHttpService().getUserAddressListSuccess { (AddressModelList, state, error) in
            Constants.window?.hideToastActivity()
            self.tableView.es.stopPullToRefresh()
            self.tableView.es.stopLoadingMore()
            if state {
                if AddressModelList.count > 0 {
                    self.dataSource += AddressModelList
                    self.resultCacheDataSource(searchStr: self.searchBar.text ?? "")
                }
            } else {
                Constants.window?.makeToast(error)
            }
           
        }
    }
    
    func setUI() {
        self.view.addSubview(self.searchView)
        self.searchView.addSubview(self.searchBar)
        self.view.addSubview(self.bottonView)
        self.view.addSubview(self.tableView)
        searchView.snp.makeConstraints { (make) in
            make.top.equalTo(self.view.snp.top).offset(0);
            make.left.equalTo(self.view.snp.left);
            make.right.equalTo(self.view.snp.right);
            make.height.equalTo(44);
        }
        searchBar.snp.makeConstraints { (make) in
            make.left.equalTo(self.searchView.snp.left);
            make.right.equalTo(self.searchView.snp.right);
            make.bottom.equalTo(self.searchView.snp.bottom);
            make.height.equalTo(44);
        }
        bottonView.snp.makeConstraints { (make) in
            make.bottom.equalTo(self.view.snp.bottom).offset(0);
            make.left.equalTo(self.view.snp.left).offset(0);
            make.right.equalTo(self.view.snp.right).offset(-0);
            make.height.equalTo(56 + Constants.xSafeBottomHeight);
        }
        tableView.snp.makeConstraints { (make) in
            make.top.equalTo(self.searchView.snp.bottom).offset(20);
            make.left.equalTo(self.view.snp.left).offset(0);
            make.bottom.equalTo(self.bottonView.snp.top).offset(-10);
            make.right.equalTo(self.view.snp.right).offset(0);
        }
    }
    @objc func clickAddBtn() {
        let editAddressC:EditAddressController = EditAddressController.init()
        editAddressC.addressListBtn.isHidden = true
        editAddressC.selectAddressBlock = { (userAddressModel,index) in
            self.getData()
        }
        self.navigationController?.pushViewController(editAddressC, animated: true)
    }
    
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        self.resultCacheDataSource(searchStr: searchText)
    }
    
    func resultCacheDataSource(searchStr:String) {
        if self.searchArr.count > 0 {
            self.searchArr.removeAll()
        }
        resultStr = searchStr
        if resultStr.count > 0 {
            for model in dataSource {
                if model.name.contains(resultStr) || model.phone.contains(resultStr) {
                    searchArr.append(model)
                }
            }
        } else {
            searchArr.append(contentsOf: dataSource)
            resultStr = ""
        }
        tableView.reloadData()
    }
    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        self.navigationController?.popViewController(animated: false)
    }
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        if resultStr == searchBar.text {
            self.resultCacheDataSource(searchStr: searchBar.text ?? "")
        }
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        tableView.tableViewDisplayMessage(message: ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.WL_notData), rowCount: dataSource.count)
        return searchArr.count
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        let model = searchArr[indexPath.row]
        if index != 0 {
            let dicData:Dictionary = ["cityId":model.cityId,"cityName":model.city,"operateType":index,"regionId":model.regionId,"regionName":model.region] as [String : Any]
            HttpService.sharedHttpService().getrecAndSendSupport(dicData: dicData) { [self] (json, state, error) in
                Constants.window?.hideAllToasts()
                if state {
                    if json["code"].int == 302 {
                        Constants.window?.makeToast(json["message"].description)
                        self.searchArr[indexPath.row].supportDelivery = true
                    } else {
                        self.searchArr[indexPath.row].supportDelivery = false
                    }
                    if (selectAddressBlock != nil) {
                        selectAddressBlock(searchArr[indexPath.row],index)
                        self.navigationController?.popViewController(animated: true)
                    }
                } else {
                    Constants.window?.makeToast(error)
                }
            }
        } else {
            if (selectAddressBlock != nil) {
                selectAddressBlock(searchArr[indexPath.row],index)
                self.navigationController?.popViewController(animated: true)
            }
        }
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        tableView.rowHeight = UITableView.automaticDimension
        tableView.estimatedRowHeight = 100
        return tableView.rowHeight
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:AddressListCell = tableView.dequeueReusableCell(withIdentifier: "cell1") as! AddressListCell
        cell.setAddressModel(addressModel: searchArr[indexPath.row])
        cell.selectionStyle = .none
        cell.addressListCellBlock = {(cell,tag) in
            let path = self.tableView.indexPath(for: cell)
            if tag == 101 {
                let editAddressC:EditAddressController = EditAddressController.init()
                editAddressC.setAddressModel(addressModel: self.searchArr[indexPath.row])
                editAddressC.selectAddressBlock = { (userAddressModel,index) in
                    self.getData()
                }
                self.navigationController?.pushViewController(editAddressC, animated: true)
            } else if tag == 102 {
                let alertt = UIAlertController.init(title: ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.hint_delete_this_address), message: "", preferredStyle: .alert)
                let cencel = UIAlertAction.init(title: ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.WL_cancel), style: .default) { (action) in
                    
                }
                let confirm = UIAlertAction.init(title: ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.WL_confirm), style: .default) { (action) in
                    Constants.window?.makeToastActivity(.center)
                    let dicData = ["id":self.searchArr[indexPath.row].id]
                    HttpService.sharedHttpService().deleteAddress(dicData: dicData) { (json, state, error) in
                        let model = self.searchArr[indexPath.row]
                        for (index,name) in self.searchArr.enumerated() {
                            if name.id == model.id {
                                self.searchArr.remove(at: index)
                            }
                        }
                        for (index,name) in self.dataSource.enumerated() {
                            if name.id == model.id {
                                self.dataSource.remove(at: index)
                            }
                        }
                    }
                }
                alertt.addAction(cencel)
                alertt.addAction(confirm)
                self.present(alertt, animated: true) {
                    
                }
            } else if tag == 103 {
                if cell.selectBtn.isSelected {
                    Constants.window?.makeToastActivity(.center)
                    HttpService.sharedHttpService().setDefaultAddress(ID: self.searchArr[indexPath.row].id) { (json, state, error) in
                        Constants.window?.hideToastActivity()
                        if state {
                            for model in self.searchArr {
                                model.isDefault = 0
                            }
                            self.searchArr[indexPath.row].isDefault = 1
                            self.dataSource[indexPath.row].isDefault = 1
                            self.resultCacheDataSource(searchStr: self.searchBar.text ?? "")
                        } else {
                            Constants.window?.makeToast(error)
                        }
                    }
                } else {
                    Constants.window?.makeToastActivity(.center)
                    HttpService.sharedHttpService().cancelDefaultAddress(ID: self.searchArr[indexPath.row].id) { (json, state, error) in
                        Constants.window?.hideToastActivity()
                        if state {
                            for model in self.searchArr {
                                model.isDefault = 0
                            }
                            self.searchArr[indexPath.row].isDefault = 0
                            self.dataSource[indexPath.row].isDefault = 0
                            self.resultCacheDataSource(searchStr: self.searchBar.text ?? "")
                        } else {
                            Constants.window?.makeToast(error)
                        }
                    }
                }
            }
        }
        return cell;
    }
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        self.isEditing = false
    }
    func setIndex(index:Int) {
        self.index = index
    }
    lazy var tableView: UITableView = {
        let tableView = UITableView.init()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = UIColor.init(hexString: "#F3F3F3")
        tableView.separatorStyle = .none
        tableView.register(UINib.init(nibName: "AddressListCell", bundle: nil), forCellReuseIdentifier: "cell1")
        tableView.keyboardDismissMode = .onDrag
        return tableView
    }()
    lazy var bottonView: UIView = {
        let bottonView = UIView.init()
        bottonView.backgroundColor = UIColor.white
        bottonView.addSubview(self.addBtn)
        addBtn.snp.makeConstraints { (make) in
            make.top.equalTo(self.bottonView.snp.top).offset(8);
            make.left.equalTo(self.bottonView.snp.left).offset(60);
            make.right.equalTo(self.bottonView.snp.right).offset(-60);
            make.height.equalTo(40);
        }
        return bottonView
    }()
    lazy var addBtn: UIButton = {
        let addBtn = UIButton.init(type: .custom)
        addBtn.setTitle(ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.WL_add_address), for: .normal)
        addBtn.layer.cornerRadius = 20
        addBtn.backgroundColor = UIColor.init(hexString: "#FFD10A")
        addBtn.setTitleColor(UIColor.init(hexString: "#000000"), for: .normal)
        addBtn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 17)
        addBtn.addTarget(self, action: #selector(clickAddBtn), for: .touchUpInside)
        return addBtn
    }()
    lazy var searchView: UIView = {
        let searchView = UIView.init()
        searchView.backgroundColor = UIColor.white
        return searchView
    }()
    lazy var searchBar: UISearchBar = {
        let searchBar = UISearchBar.init()
        searchBar.delegate = self
        searchBar.searchBarStyle = .minimal
        searchBar.barStyle = .default
        searchBar.placeholder = ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.hint_import_phoneAndName)
        
        let seachTextFild:UITextField = searchBar.value(forKey: "searchField") as! UITextField
        seachTextFild.font = UIFont.systemFont(ofSize: 14)
        return searchBar
    }()
    


}
